import { Component, ElementRef, Renderer2 } from '@angular/core';
import { ApesField } from '@shared/ui-zorro/src/types/apes-field';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { Events } from '@core/services/events/Events';
import { SubjectService } from '@core/services/events/subject.service';
import { ApiService } from '@core/services/http/api.service';
import { deepClone } from '../../../../utils/utils';
import { toBoolean } from '@shared/apes/core';

@Component({
  selector: 'formly-field-button',
  template: `
    <button *ngIf="setBtnVisible()"
            apes-button
            [disabled]="disabled()"
            [apesLoading]="isLoading"
            [apesType]="btnType"
            class="fieldButton">{{to.label}}</button>


    <!--     <ng-container *ngFor="let button of list">-->
    <!--      <button apes-button (click)="setCurrentButton(button)">{{button.label}}</button>-->
    <!--     </ng-container>-->
  `,
  styles: [`
    .fieldButton[disabled] {
      border-color: #ddd;
    }
  `],
})
/*按钮*/
export class FormlyFieldButton extends ApesField {
  list = [];
  // currentButton: any;
  btnType;
  ctx: any;
  model: any;
  auth: boolean = false;
  dynamicStatus: boolean = false;
  isDisabled: boolean = false;
  isLoading: boolean = false;

  constructor(protected apiService: ApiService, protected events: Events,
              protected expressionService: ExpressionService, protected subject: SubjectService,
              protected elementRef: ElementRef, protected renderer: Renderer2) {
    super(apiService, events, expressionService, subject);
  }

  ngOnInit(): void {
    this.addEventListener(this.elementRef, this.renderer);
    this.btnType = this.to.btnType ? this.to.btnType : 'primary';
    this.dynamicStatus = this.to.dynamicStatus ? this.to.dynamicStatus : false;
    this.ctx = this.formState;
    if (this.to.hasOwnProperty('auth')) {
      this.auth = true;
    }
    this.subject.subscribe(this.formState, 'button_' + this.key, data => {
      this.isDisabled = data.disabled ? toBoolean(data.disabled) : false;
      this.isLoading = data.loading ? toBoolean(data.loading) : false;
    });
  }

  setBtnVisible() {
    if (!this.auth) {
      return true;
    } else {
      let check = false;
      let btnBar = deepClone(this.ctx['customBtn']);
      btnBar.forEach((btn) => {
        if (btn.id == this.key) {
          check = true;
        }
      });
      return check;
    }
  }

  disabled() {
    if (this.dynamicStatus) {
      return this.isDisabled;
    } else {
      return this.to.disabled;
    }
  }

  // setCurrentButton(button) {
  //   this.currentButton = button;
  // }
}

